#!/usr/bin/env python 3.6
# -*- coding: utf-8 -*-
# @Time      :2019/2/14
# @Author    :Tian Maohong
# @Email     :tianmaohong@bbdservice.com
# @File      :TAX21_Ent2yearsTaxVioTypeCnt_SC
# @Software  :PyCharm


import json
import re
import sys
import datetime
import pandas as pd
from dateutil.relativedelta import relativedelta

'''eof
name:申请企业近两年严重税务违法违章类型
code:TAX21_Ent2yearsTaxVioTypeCnt_SC
tableName:
columnName:
groups:场景业务校验-税务
dependencies:TX_SC_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''


# reload(sys)
# sys.setdefaultencoding('utf-8')


def inquireIsReportNo(data):
    """
    判断是否存在reportNo
    :param data:
    :return:True/False
    """
    try:

        is_reportNo = True if len(data.get("reportNo")) > 0 else False

    except:
        is_reportNo = False

    return is_reportNo


def formatData(table_Name):
    """
    获取数据
    :param table_Name:字典keys
    :return:[{}]
    """
    try:
        data = TX_SC_DSJ["data"].get(table_Name)
        return data if isinstance(data, list) and len(data) > 0 else [{}]
    except:
        return None


def convertDataType(data_value, data_type):
    """
    数据格式转换
    :param data_value:
    :param data_type: float/int/str/date_time
    :return:
    """
    data_value = str(data_value)
    return_data = None
    # float
    if data_type == 'float':
        try:
            return_data = float(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # int
    elif data_type == 'int':
        try:
            return_data = int(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # str
    elif data_type == 'str':
        try:
            return_data = str(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # date_time
    elif data_type == 'date_time':
        r = re.compile(r'\D+')
        try:
            return_data = datetime.datetime.strptime(data_value, '%Y.%m.%d').strftime('%Y-%m-%d')
        except:
            try:
                return_data = datetime.datetime.strptime(data_value, '%Y-%m-%d').strftime('%Y-%m-%d')
            except:
                try:
                    return_data = datetime.datetime.strptime(data_value, '%Y/%m/%d').strftime('%Y-%m-%d')
                except:
                    try:
                        return_data = datetime.datetime.strptime(data_value, '%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d')
                    except:
                        try:
                            data_value = r.sub('', data_value)
                            return_data = datetime.datetime.strptime(data_value, '%Y%m%d').strftime('%Y-%m-%d')
                        except:
                            return_data = None

    return return_data

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def entIllegalRecordBadTaxCheck(putBackYear=2, CcrDate=None):
    """
    企业不良纳税记录校验（违法违章记录）
    :return:
    """
    syptWfwzxx = formatData('syptWfwzxx')

    # 生成时间轴
    dateIndexList = []
    if CcrDate is None:
        CcrYearMonth = datetime.datetime.now().strftime('%Y-%m-%d')[:7]
        CcrDate = CcrYearMonth + '-01'
        StartDateTmp = str(datetime.datetime.now().year - putBackYear) + CcrDate[4:]
        StartDate = StartDateTmp[:7] + '-01'
    else:
        CcrYear = datetime.datetime.strptime(convertDataType(CcrDate, 'date_time'), '%Y-%m-%d').date().year
        CcrDate = convertDataType(CcrDate, 'date_time')[:7] + '-01'
        StartDate = str(CcrYear - putBackYear) + convertDataType(CcrDate, 'date_time')[4:]

    dateSet = pd.date_range(StartDate, CcrDate, freq='M')
    for i in dateSet:
        year = i.date().year
        month = i.date().month
        dateIndexList.append(str(year) + str(month))

    if syptWfwzxx == [{}]:
        return 1
    elif syptWfwzxx is None:
        return u'缺失值'
    else:
        two_years_ago = datetime.datetime.now() - relativedelta(months=24)
        # rejectList = [u'逃避缴纳税款', u'骗税', u'抗税', u'逃避追缴欠税', u'其他违法']
        rejectList = [u'01', u'02', u'03', u'09'] # 删除99
        FactorList = []
        for i in range(len(syptWfwzxx)):
            WFWZLX_DM = convertDataType(syptWfwzxx[i].get('WFWZLX_DM'), 'str')
            if WFWZLX_DM in rejectList:
                if syptWfwzxx[i].get('LARQ') is None:
                    FactorList.append(0)
                    continue
                LARQ = convertDataType(syptWfwzxx[i].get('LARQ')[:10], 'date_time')
                if LARQ in null_type_list:
                    FactorList.append(0)
                    continue
                LARQ = datetime.datetime.strptime(LARQ, '%Y-%m-%d')
                if LARQ > two_years_ago:
                    FactorList.append(0)
                else:
                    FactorList.append(1)
            else:
                FactorList.append(1)

        # 逻辑判断
        if 0 in FactorList:
            Factor = 0
        else:
            Factor = 1

        return Factor


result = entIllegalRecordBadTaxCheck()

# try:
#     if __name__ == '__main__':
#         # 下面添加需要执行的函数
#         # 读取json文件
#         file_obj = open(r'G:\\BBDWork\\project\\modelMigration\\data\\TX_SC_DSJ_NEW.js', 'r')
#         content = file_obj.read()
#         TX_SC_DSJ = json.loads(content, strict=False)['TX_SC_DSJ']
#
#         # 审批时间
#         spDateTime = '20170812'
#
#         # 连续性纳税校验
#         # aa = entOwePaidBadTaxCheck()
#         aa = entIllegalRecordBadTaxCheck(CcrDate=spDateTime)
#         t = aa
#         pass
# except Exception as e:
#     print('exception happen')
#     raise e